# -*- coding: utf-8 -*-

import subprocess


# 数据库配置
DB_HOST = 'localhost'
DB_PORT = 3306
DB_USER = 'root'
DB_PSWD = 'Mariadb119'
DB_NAME = 'testDB'


def check_and_drop_database():
    # 使用subprocess执行sql命令 来检查数据库是否存在
    cmd = f"mysql -u {DB_USER} -p{DB_PSWD} -h {DB_HOST} -P {DB_PORT} -e \"SHOW DATABASES LIKE \'{DB_NAME}\'\""
    result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if result.returncode == 0 and 'testDB' in result.stdout:
        print(f"Database 'testDB' exists!")

        # 如果存在, 则删除数据库
        drop_cmd = f"mysql -u {DB_USER} -p{DB_PSWD} -h {DB_HOST} -P {DB_PORT} -e \"DROP DATABASE IF EXISTS {DB_NAME}\""
        subprocess.run(drop_cmd, shell=True, check=True, text=True)
        print(f"Database 'testDB' has been dropped!")
    else:
        print(f"Database 'testDB' does not exist!")

    # 创建数据库的命令
    create_cmd = f"mysql -h {DB_HOST} -P {DB_PORT} -u {DB_USER} -p{DB_PSWD} -e \"CREATE DATABASE {DB_NAME}\""
    subprocess.run(create_cmd, shell=True, check=True, text=True)

